//
//  RouterControllerMixin.swift
//  DYSwiftFramework
//
//  Created by huangdeyu on 2021/10/18.
//  Copyright © 2021 none. All rights reserved.
//

import Foundation
import UIKit


protocol RouterControllerMixin : AssociatedObjects {
    // 作为路由节点
    var routerNode:RouterNode?{ get  set}
    // 页面启动数据
    var launchData:Any?{ get set}
    var routerPath:String?{ get }
    var routerFragment:Int { get }
    var backAction:((Any?)->Void)? { get set}
    func routerDescription() -> Void
    
}

private var nodeKey:UInt8 = 0

extension RouterControllerMixin  where Self : UIViewController  {
    
    var routerNode:RouterNode? {
        get {
            return associatedObject(for: &nodeKey)
        }
        set (value) {
            setAssociatedObject(value, for: &nodeKey, policy: AssociationPolicy.strong)
        }
    }
    
    /// 启动数据
    var launchData:Any?{
        get {
            return routerNode?.launchData
        }
        set(value){
            routerNode?.launchData = value
        }
    }
    
    /// 对应当前的路径，只读
    var routerPath:String?{
        get {
            if routerNode == nil {
                return nil;
            }
            if navigationController == nil {
                 return routerNode?.name
            }
            if let p = routerNode?.path {
                if !p.isEmpty{
                    return routerNode?.path
                }
            }
            var tempPath = ""
            navigationController?.viewControllers.forEach({ (vc) in
                if vc is RouterControllerMixin {
                    tempPath  += "/" +   (vc as! RouterControllerMixin).routerNode!.name
                }
            })
            routerNode?.path = tempPath
            return tempPath
        }
    }
    
    // 当前页面堆栈下的相同页面数量，只读
    var routerFragment:Int{
        get {
            if routerNode == nil {
                return 0
            }
            if navigationController == nil {
                return 0
            }
            var count:Int = 0
            for item in navigationController!.viewControllers {
                if item is RouterControllerMixin {
                    if (item as! RouterControllerMixin).routerNode!.name == self.routerNode!.name{
                        count += 1
                    }
                    if item === self {
                        break
                    }
                }
            }
            return count
        }
    }
    
    var backAction:((Any?)->Void)?{
        get{
            return routerNode?.backAction
        }
        set(value){
            routerNode?.backAction = value
        }
    }
    
    func routerDescription(){
        if let node = routerNode {
            debugPrint("-------\(String(describing: node.instance))路径是:\(routerPath!)#\(routerFragment)")
        }
    }
}
